import {
  getToken,
  setStorageItem,
  getStorageItem
} from '../../../../utils/storage.js';
import {
  addQrCode
} from '../../../../api/comment.js';
import {
  showWxToast
} from '../../../../utils/index.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    qrCodeUrl: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取用户二维码
    this.setData({
      'qrCodeUrl': getStorageItem('comment_json')
    })
    // 判断是否有二维码，没有则直接调用进行上传操作
    if(!this.data.qrCodeUrl) {
      this.uploadQR();
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },
  // 上传二维码的逻辑
  uploadQR() {
    wx.chooseMedia({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      mediaType: ['image'],
      success: (res) => {
        console.log('选择图片', res);
        const tempFilePaths = res.tempFiles
        const tmpToken = getToken();
        wx.uploadFile({
          filePath: tempFilePaths[0].tempFilePath,
          name: 'file',
          header: {
            'token': tmpToken,
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          url: 'https://www.hudongmiao.com/beiJing/shangchuanTomcat',
          success: (res) => {
            let webidpic = JSON.parse(res.data);
            setStorageItem('comment_json', webidpic.data.filePath)
            this.setData({
              qrCodeUrl: webidpic.data.filePath
            })
            this.addQrCode(webidpic.data.filePath)
          }
        })
      }
    })
  },
  // 上传二维码接口
  addQrCode(comment_json) {

    addQrCode(comment_json).then(res => {
        showWxToast('操作成功')
      })
      .catch(err => {
        showWxToast('操作失败')

      })
  },
  // 删除当前用户的二维码
  removeImg() {
    wx.showModal({
      title: '',
      content: '确定要移除二维码吗',
      success: (res) => {

        if (res.confirm) {
          this.setData({
            qrCodeUrl: '',
          })
          setStorageItem('comment_json', '')
          this.addQrCode('')
        } else if (res.cancel) {
          showWxToast('已取消')
        }

      }

    })
  },
})